﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Text;
using T.FAS.Runtime.Base.Dao;
using T.FAS.Runtime.ScheduleJob.SPI;
using T.ServiceComponent.DAC.Service;
using T.ServiceComponent.DataAccessEx.Core;

namespace T.FAS.Runtime.ScheduleJob.Dao
{
    public class ScheduleJobSubscriptionFrequencyDao : DaoService<ScheduleJobSubscriptionFrequency>
    {
        public override string TableName => "FAS_SubscriptionFrequency";
        public override string IDColumnName => "ID";

        public override List<string> ExceptColumnName
            => DaoUtil.GetExceptionColumn<ScheduleJobSubscriptionFrequency>(
                new List<string>
                {
                }
            );
        public ScheduleJobSubscriptionFrequencyDao() : base()
        {
            DBName = "TFAS";
        }
        private SysExecuteFrequencyDao sysFrequencyDao = new SysExecuteFrequencyDao();
        public override ScheduleJobSubscriptionFrequency ConvertToObject(Dictionary<string, PropertyInfo> columns, DataRow row)
        {
            if (columns.ContainsKey("FrequencyType"))
                columns.Remove("FrequencyType");
            var data = base.ConvertToObject(columns, row);
            data.FrequencyType = (FrequencyType)Enum.Parse(typeof(TriggerType), Convert.ToString(row["FrequencyType"]));
            return data;
        }
        public override Dictionary<string, object> GetDataMapping(ScheduleJobSubscriptionFrequency data)
        {
            var mapping = base.GetDataMapping(data);

            mapping.Remove("FrequencyType");
            mapping.Add("FrequencyType", (int)data.FrequencyType);
            return mapping;
        }
        public override Dictionary<string, PropertyInfo> GetColumns()
        {
            return base.GetColumns();
        }

        public void AddScheduleJobSubscriptionFrequency(ScheduleJobSubscriptionFrequency data)
        {
            if (data != null)
            {
                if (string.IsNullOrEmpty(data.ID))
                    data.ID = Guid.NewGuid().ToString();
                base.Add(new List<object>() { data });
                if (data.SysFrequencies != null)
                {
                    int sort = 0;
                    //关联关系更新
                    data.SysFrequencies.ForEach(f =>
                    {
                        var sysFrequency = sysFrequencyDao.GetExecuteFrequencyByID(f.ID);
                        if (sysFrequency != null)
                        {
                            List<IDbDataParameter> paramList = new List<IDbDataParameter>();
                            paramList.Add(DB.MakeInParam("@ID", TDbDataType.VarChar, Guid.NewGuid().ToString()));
                            paramList.Add(DB.MakeInParam("@SubscriptionFrequencyID", TDbDataType.VarChar, data.ID));
                            paramList.Add(DB.MakeInParam("@sysExecuteFrequencyID", TDbDataType.VarChar, f.ID));
                            paramList.Add(DB.MakeInParam("@SortOrder", TDbDataType.Int, sort));
                            var insertSql = "insert into FAS_SubscriptionFrequencyRelation (ID,SubscriptionFrequencyID,sysExecuteFrequencyID,SortOrder) values (@ID,@SubscriptionFrequencyID,@sysExecuteFrequencyID,@SortOrder)";
                            DB.ExecSqlStatement(insertSql, paramList.ToArray());
                            sort++;
                            //填充系统执行频率数据
                            sysFrequency.CopyTo(f);
                        }
                    });
                }
            }
        }
        public ScheduleJobSubscriptionFrequency GetScheduleJobSubscriptionFrequencyBySubId(string subId)
        {
            var result = base.GetObjectsByFilter($"ScheduleJobSubscriptionID='{subId}'");
            if (result == null || result.Count <= 0)
                return null;
            var frequency = result[0] as ScheduleJobSubscriptionFrequency;
            if (frequency.FrequencyType == FrequencyType.SysFrequency)
            {
                frequency.SysFrequencies = new List<SysExecuteFrequency>();
                var paramList = new List<IDbDataParameter>()
                {
                    DB.MakeInParam("@SubscriptionFrequencyID",TDbDataType.VarChar,frequency.ID)
                };
                var getSql = "select ID,SubscriptionFrequencyID,SysExecuteFrequencyID,SortOrder from FAS_SubscriptionFrequencyRelation where SubscriptionFrequencyID = @SubscriptionFrequencyID order by SortOrder";
                var relationDs = DB.ExecuteDataSet(getSql, paramList.ToArray());
                if (relationDs != null && relationDs.Tables != null && relationDs.Tables.Count > 0 && relationDs.Tables[0].Rows != null && relationDs.Tables[0].Rows.Count > 0)
                {
                    foreach (DataRow row in relationDs.Tables[0].Rows)
                    {
                        var sysFrequencyId = Convert.ToString(row["SysExecuteFrequencyID"]);
                        var sysFrequency = sysFrequencyDao.GetExecuteFrequencyByID(sysFrequencyId);
                        if (sysFrequency!=null && !frequency.SysFrequencies.Exists(f => f.ID.Equals(sysFrequency)))
                        {
                            frequency.SysFrequencies.Add(sysFrequency);
                        }
                    }
                }
            }
            return frequency;
        }

        public void DeleteScheduleJobSubscriptionFrequency(string subscriptionID)
        {
            var frequency = GetScheduleJobSubscriptionFrequencyBySubId(subscriptionID);
            if (frequency != null && frequency.SysFrequencies!=null && frequency.SysFrequencies.Count>0)
            {
                frequency.SysFrequencies.ForEach(f =>
                {
                    var freParameter = DB.MakeInParam("@ID",TDbDataType.VarChar,f.ID);
                    DB.ExecSqlStatement("Delete from FAS_SubscriptionFrequencyRelation where ID = @ID",freParameter);
                });
            }
            var parameter = DB.MakeInParam("@SubscriptionID", TDbDataType.VarChar, subscriptionID);
            DB.ExecSqlStatement(string.Format("delete from {0} where ScheduleJobSubscriptionID = @SubscriptionID",this.TableName),parameter);
        }
    }
}
